package com.yj.auto.plugin.lucene.model;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LogByteSizeMergePolicy;
import org.apache.lucene.index.LogMergePolicy;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;

import com.jfinal.log.Log;
import com.yj.auto.plugin.lucene.utils.LuceneUtil;

//索引写入器
public class AutoIndexWriter {

	private static final Log logger = Log.getLog(AutoIndexWriter.class);

	private IndexWriter writer = null;

	public AutoIndexWriter() throws Exception {
		Directory dir = LuceneUtil.getDirectory();
		Analyzer analyzer = LuceneUtil.getAnalyzer();
		IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
		LogMergePolicy mergePolicy = new LogByteSizeMergePolicy();
		// 设置segment添加文档(Document)时的合并频率 ,值较小,建立索引的速度就较慢 ,值较大,建立索引的速度就较快,>10适合批量建立索引
		mergePolicy.setMergeFactor(50);
		// 设置segment最大合并文档(Document)数 ,值较小有利于追加索引的速度 ,值较大,适合批量建立索引和更快的搜索
		mergePolicy.setMaxMergeDocs(5000);
		iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
		writer = new IndexWriter(dir, iwc);
	}

	public IndexWriter getIndexWriter() {
		return writer;
	}

	protected long commit() throws Exception {
		long seqNo = writer.commit();
		return seqNo;
	}

	protected void close() throws Exception {
		writer.close();
	}

	// 最后一定要调用 release() 否则索引文件将被锁住
	public boolean release() {
		boolean success = true;
		try {
			commit();
		} catch (Exception e) {
			logger.error("commit index writer error", e);
			success = false;
		}
		try {
			close();
		} catch (Exception e) {
			logger.error("close index writer error", e);
			success = false;
		}
		return success;
	}

	public long addDocument(Document doc) throws Exception {
		return writer.addDocument(doc);
	}

	public long updateDocument(Term term, Document doc) throws Exception {
		return writer.updateDocument(term, doc);
	}

	public long deleteDocuments(Term... terms) throws IOException {
		return writer.deleteDocuments(terms);
	}
}
